x = 10
x
10
print(x)
10
x = x + x
print(x)
x = x * 2
print(x)
x = x ** (x / 89)
print(x)
x = x / 12
print(x)
x = x % 11
print(x)
20 40 5.248400429918207 0.43736670249318393 0.43736670249318393
for i in range(11):
print(i*i)
0 1 4 9 16 25 36 49 64 81 100
The most important python imaging library is Image. It is imported from PIL like this
from PIL import Image
To open an image, use the .open() function from the Image module. Specify the path in the .open() function. Here the file path is just the filename, 'colorshape.png' which is in the same directory as the .ipnb file itself. It is to read from the disk.
image = Image.open('colorshape.png')
To print the format of the image use the .format attribute. If it is not read from the file, it will return a None. Here the format is 'JPEG' format.
image.format
'JPEG'
The image size is given by .size() function from the Image module. It gives the width and height in pixels and is a tuple type. The width here is 186 pixels and the height is 271 pixels.
image.height
271
image.width
186
image.size
(186, 271)
The mode of the image is given by the .mode attribute which gives the number and names of the band in the image. Here, the mode is 'RGB' which means the image is in Red, Blue, Green or in the true colors.
image.mode
'RGB'
To show the image, use the .show() method which takes in no parameters. It is not very efficient as it stores the image in a temporary utility and displays it from that utility.
image.show()
image
Enhancing images can be possible by ImageEnhance package from the PIL library in python. The brightness, contrast, sharpness, etc. are a few enhancing factors.
from PIL import ImageEnhance
image = Image.open('pinkfloyd.ppm')
image
The class, Brightness is used to change the brightness of the image. The enhance() method is used to specify the factor with which the the image should be modified.
enhancer_brightness = ImageEnhance.Brightness(image)
enhancer_brightness.enhance(0.5)
The class, Sharpness is used to change the brightness of the image. The enhance() method is used to specify the factor with which the the image should be modified.
enhancer_sharpness = ImageEnhance.Sharpness(image)
enhancer_sharpness.enhance(0.5)
Images can be pasted on top of each other using the paste() option. It takes in three parameters which are image on which the other image is to be pasted, the image to be pasted and a tuple of coordinates of the top left corner of where the pasted image should start from where the image is to be pasted. This modifies the base image. So here the image2's top left corner is (20,30) from (0,0) or image1's top left corner.
from PIL import Image
image1 = Image.open('colorshape.png')
image2 = Image.open('pinkfloyd.ppm')
Image.Image.paste(image1,image2,(20,30))
image1
Here, the second image is been cropped out because it has a bigger width than the width of the base image. So use the resize option to get the image to fit in without cropping using resize() method which takes in two parameters that are image half width and image half height.
from PIL import Image
image1 = Image.open('colorshape.png')
image2 = Image.open('pinkfloyd.ppm')
image2 = image2.resize((round(image2.size[0] * 0.5), round(image2.size[1] * 0.5)))
Image.Image.paste(image1,image2,(20,30))
image1
To create an empty canvas, use new() method which takes in the mode, size and color of the canvas. The mode is 'RGB' here and the size is 200 width pixels by 300 height pixels. Pasting on top of canvas is very useful as well.
from PIL import Image
canvas = Image.new(mode = 'RGB', size = (200, 300), color = (200,200,20))
canvas
canvas = canvas.resize((round(canvas.size[0] * 2), round(canvas.size[1] * 2)))
Image.Image.paste(canvas,image1,(80,30))
canvas
Convert images into different scales is done by the .convert() function which takes in mode which is compulsory.
canvas.convert(mode = "L")
matrix = (1,0,0,0,
0,1,0,0,
0,0,1,0)
canvas.convert('RGB',matrix)
canvas_crop = canvas.crop((30,30,180,180))
canvas_crop
canvas = canvas.resize((round(canvas.size[0] * 0.2), round(canvas.size[1] * 0.2)))
contact = []
matrix_red = (1,0,0,0,
0,0,0,0,
0,0,0,0)
canvas_red = canvas.convert('RGB',matrix_red)
enhancer_brightness = ImageEnhance.Brightness(canvas_red)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_red)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_red)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
matrix_green = (0,0,0,0,
0,1,0,0,
0,0,0,0)
canvas_green = canvas.convert('RGB',matrix_green)
enhancer_brightness = ImageEnhance.Brightness(canvas_green)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_green)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_green)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
matrix_blue = (0,0,0,0,
0,0,0,0,
0,0,1,0)
canvas_blue = canvas.convert('RGB',matrix_blue)
enhancer_brightness = ImageEnhance.Brightness(canvas_blue)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_blue)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_blue)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
matrix_aqua = (0.05,0.05,0.05,0.00,
0.05,1.00,0.05,0.00,
0.05,0.05,1.00,0.00)
canvas_aqua = canvas.convert('RGB',matrix_aqua)
enhancer_brightness = ImageEnhance.Brightness(canvas_aqua)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_aqua)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_aqua)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
matrix_magenta = (1.00,0.05,0.05,0.00,
0.05,0.05,0.05,0.00,
0.05,0.05,1.00,0.00)
canvas_magenta = canvas.convert('RGB',matrix_magenta)
enhancer_brightness = ImageEnhance.Brightness(canvas_magenta)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_magenta)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_magenta)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
matrix_yellow = (1.00,0.05,0.05,0.00,
0.05,1.00,0.05,0.00,
0.05,0.05,0.05,0.00)
canvas_yellow = canvas.convert('RGB',matrix_yellow)
enhancer_brightness = ImageEnhance.Brightness(canvas_yellow)
contact.append(enhancer_brightness.enhance(0.1))
enhancer_brightness.enhance(0.1)
enhancer_brightness = ImageEnhance.Brightness(canvas_yellow)
contact.append(enhancer_brightness.enhance(0.5))
enhancer_brightness.enhance(0.5)
enhancer_brightness = ImageEnhance.Brightness(canvas_yellow)
contact.append(enhancer_brightness.enhance(0.9))
enhancer_brightness.enhance(0.9)
print(len(contact))
18
canvas.size, canvas.width, canvas.height
((80, 120), 80, 120)
contact_canvas = Image.new(mode = 'RGB', size = (canvas.width * 6, canvas.height * 3), color = (50,200,130))
contact_canvas
x = 0
y = 0
for i in contact:
Image.Image.paste(contact_canvas,i,(x,y))
if x == 5 * canvas.width:
y = y + canvas.height
x = 0
else:
x = x + canvas.width
contact_canvas
canvas
canvas_copy = canvas.copy()
canvas_copy = canvas_copy.resize((canvas_copy.width * 10, canvas_copy.height * 10))
from PIL import ImageFilter
canvas_copy = canvas_copy.filter(ImageFilter.BLUR)
canvas_copy = canvas_copy.filter(ImageFilter.MedianFilter(size = 3))
canvas_copy = canvas_copy.filter(ImageFilter.BoxBlur(10))
canvas_copy = canvas_copy.filter(ImageFilter.SHARPEN)
canvas_copy = canvas_copy.filter(ImageFilter.EMBOSS)
canvas_copy.save('copy.jpg')
from IPython.display import display
display(canvas_copy)
from PIL import ImageDraw
Image.Image.paste(canvas_copy,contact_canvas,(20, canvas_copy.height//2 + 100))
canvas_copy
canvas_copy_box = ImageDraw.Draw(canvas_copy)
canvas_copy_box.rectangle([(120,30),(150,90)],fill="orange",outline="green")
canvas_copy
canvas_copy_box_text = ImageDraw.Draw(canvas_copy)
from PIL import ImageFont
f = ImageFont.truetype(r'./Pacifico.ttf',50)
text = 'Oh \n Cool'
canvas_copy_box_text.text((490,490),text,font = f, align="right")
canvas_copy
canvas_copy = canvas_copy.convert('1').convert('L')
canvas_copy
from PIL import Image
image = Image.open(r'C:\Users\harshulmehul\Documents\GitHub\Projects\5. BITS Hyd Proj\1. Python\handprint.jpg')
image_copy = image.copy()
image_copy_grey = image.copy()
display(image)
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
dir(pytesseract)
['ALTONotSupported', 'Output', 'TSVNotSupported', 'TesseractError', 'TesseractNotFoundError', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'get_languages', 'get_tesseract_version', 'image_to_alto_xml', 'image_to_boxes', 'image_to_data', 'image_to_osd', 'image_to_pdf_or_hocr', 'image_to_string', 'pytesseract', 'run_and_get_output']
help(pytesseract)
Help on package pytesseract:
NAME
pytesseract - # flake8: noqa: F401
PACKAGE CONTENTS
pytesseract
FILE
c:\users\harshulmehul\appdata\local\programs\python\python38-32\lib\site-packages\pytesseract\__init__.py
image.mode
'RGB'
image.size
(519, 380)
for i in range(1, 4):
image = image.resize((image.width * i, image.height * i))
display(image)
text = pytesseract.image_to_string(image)
print(text)
ext from the image above is: ad oviling
The extracted text from the image above is: ad oviling
The extracted text from the image above ts: ad oviling
import inspect
print(inspect.getsource(pytesseract.image_to_string))
def image_to_string(
image,
lang=None,
config='',
nice=0,
output_type=Output.STRING,
timeout=0,
):
"""
Returns the result of a Tesseract OCR run on the provided image to string
"""
args = [image, 'txt', lang, config, nice, timeout]
return {
Output.BYTES: lambda: run_and_get_output(*(args + [True])),
Output.DICT: lambda: {'text': run_and_get_output(*args)},
Output.STRING: lambda: run_and_get_output(*args),
}[output_type]()
display(image_copy)
import PIL
from PIL import Image
for i in range(200, 205):
image_copy = image_copy.resize((int(i * image_copy.width / 100), int(i * image_copy.height / 100)), PIL.Image.ANTIALIAS)
display(image_copy)
text = pytesseract.image_to_string(image_copy)
print(text)
The extracted text from the image above is: ad oviling
The extracted text from the image above is: ad oviling
Result: The extracted text from the image above ts: ad oviling
Result: The extracted text from the image above ts: ad oviling
The extracted text from the image above ts: ad oviling
image_copy_grey_1 = image_copy_grey.copy()
image_copy_grey = image_copy_grey.convert('L')
text = pytesseract.image_to_string(image_copy_grey)
text
'The extracted text from the image abov\n\n \n\x0c'
image_b = image_copy_grey_1.copy()
image_copy_grey_1 = image_copy_grey_1.convert('1')
display(image_copy_grey_1)
def binarize(image, thresh):
output = image.convert("L")
for x in range(output.width):
for y in range(output.height):
if output.getpixel((x,y)) < thresh:
output.putpixel((x,y), 0)
else:
output.putpixel((x,y), 255)
return output
for thresh in range(0,257, 16):
image_b = binarize(Image.open('patterntext.png'), thresh)
display(image_b)
print(pytesseract.image_to_string(binarize(image_b, thresh)))
Mid Splordicr of the various-vestes! Nig
Mother ol wildleavoring visions! buil
Tisai thy didivs, while wth watery light
‘Thy week cys gimmers Brough a Eeecy well
And set eu that lovest thy pale orb to strand
Belind the gatherd Eleck-wss lost om highs
Aud wheat thon cartest foo te wind-rent cond
Thy placid yktving o'er the awaku’d sky.
Mid Spleudscr of the various-vested: Nizhel Motlice of wikdly-svor’sing visions! bul! Tisatch thy gliding, while with watery light Thy wees eye Aud sheu tha lev Bohind tha: gathes’d Aud whes Use Eurte Thy pracid Egltning o'er the awakeu'd sky. mors Eeousch a Beecy veil vy pale orb wy stroud ‘havss lost on high; cr the wine-rent clond
Md Splendscr of the various-vested Night! Mather of wiklly-working visions! buill WY Gliding, while with watery light nmers Ceough a Heecy vel Aud shen thou lovest thy pale orb to slarond Behind the guther'd bleckness lost on high; Aud vehea thon ¢artest from the wind-rent cloud Thy placid gltning o'er the awakeu’d sky,
Mftd Splendser of the various-vested Night! Mother ot wiklly-working visions! hull Twatch thy ¢lidins, while with watery light Thy weak miners through a fleccy vells Aud whe thou Jevest thy y pale orb to stirond Behind the gather'd bleckness lost on high; Aud vehea thou dartest from the wine-rent cloud Thy placid Eglining o'er the awakeu’d sky,
Mild Splendour of the various-vested Night! Mother of wiklly-working visions? builf Twatch thy gliding, while with watery light ‘Thy weak nmers through a fleccy vells dnd wkea thou Jovest thy pale orb to shrond Behind the gather'd blackness lost on highs Aud shea thou dartest fom the windrent cloud Thy placid lighting o'er the awakun’d sky,
Mild Splendour of the various-vested Night! Mother of wildly-working visious! huilf Twatch thy gliding, while with watery light Thy weak eye giimmers through a Beecy veil And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost om high; Aud when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken’d sky,
Mild Splendour of the various-vested Night! Mother of wildly-working visions! hailf I watch thy gliding, while with watery light Thy weak eye glimmers through a feeey vei And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on highs And when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken'd sky.
Mitd Splendour of the various-vested Night! Mother of wildly-working visions! half I watch thy gliding, while with watery light Thy weak eye glimmers through a fleecy veil; And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on high; And when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken'd sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! hailf T watch thy gliding, while with watery light Thy weak eye glimmers through a fleecy veil; And when thou lovest thy pale orb to shroud Behind the gather'd blackness lest on high; And when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken'd sky.
Mild Splendour of the various-vested Night! Mother of wildly.working visions! hall I watch thy gliding, while with watery light Thy weak eye glimmers through a fleecy veil; And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on high; ‘And when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken'd sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! haill T watch thy gliding, while with watery light Thy weak eye glimmers through a fleecy veil, And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on high; ‘And when thou dartest from the wind-rent cloud Thy placid lighting o'er the awaken'd sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! haill I watch thy gliding, while with watery Bight Thy weak eye glimmers through « feecy veils ‘And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on high; ‘And when thou dartest from the wind-rent cloud Thy placid lightning o'er the awaken'd sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! baill I watch thy gliding, while with watery ght Thy weak eye glimmers through a feecy veil; ‘And when thon lovest thy pale orb to shroud Behind the gather'd blackness lost on high; ‘And when thou dartest from the wind-rent cloud ‘Thy placid lightning o'er the awaken’d sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! haill I watch thy gliding, while with watery Hght Thy weak eye glimmers through a fleecy veil; ‘And when thou lovest thy pale orb to shroud. Behind the gather'd blackness lost on highs ‘And when thou dartest from the wind-reut cloud Thy placid lightning o'er the awolken’a sky.
Mild Splendour of the various-vested Night! Mother of wildly-working visions! aill watch thy gliding, while with watory Hight ‘Thy weak eye glimmers through a fleocy veil; ‘And when thou lovest thy pale orb to shroud Behind the gather'd blackness lost on high; ‘And when thou dartest from the wind-rent cloud ‘Thy placid lightning o'er the awoken’a eky.
from PIL import Image
image = Image.open('perfect.jpg')
display(image)
image.mode
'RGB'
pytesseract.image_to_string(image)
'FNOTYUIN WIAR te eS\n\nI~»\na\n\nla azine os _ &\n\nMAPFRE\n\nNX\na\nTempeASOne Oy LNBINI TI!\n\n_ es HYBRID\n\nea\n\n~ XW.\n\nCe castro 4 lela\n\n8 mec ~ALPHATAURI\n\n \n\n \n\nSRAVENOL<\n\x0c'
bounding_box = (70,300,165,325)
extract1 = image.crop(bounding_box)
display(extract1)
pytesseract.image_to_string(extract1)
'RENAULT\n\x0c'
bounding_box = (900,1350,1100,1400)
extract1 = image.crop(bounding_box)
display(extract1)
pytesseract.image_to_string(extract1)
'\x0c'
display(extract1.resize((extract1.width*5, extract1.height*5), Image.NEAREST))
display(extract1.resize((extract1.width*5, extract1.height*5), Image.BOX))
display(extract1.resize((extract1.width*5, extract1.height*5), Image.BILINEAR))
display(extract1.resize((extract1.width*5, extract1.height*5), Image.HAMMING))
display(extract1.resize((extract1.width*5, extract1.height*5), Image.BICUBIC))
display(extract1.resize((extract1.width*5, extract1.height*5), Image.LANCZOS))
options=[Image.NEAREST, Image.BOX, Image.BILINEAR, Image.HAMMING, Image.BICUBIC, Image.LANCZOS]
for option in options:
display(extract1.resize((extract1.width*5, extract1.height*5), option))
if option == Image.BICUBIC:
extract = extract1.resize((extract1.width*5, extract1.height*5), option)
print(pytesseract.image_to_string(extract))
def binarize(image1, thresh):
image = image1.convert('L')
for x in range(image.width):
for y in range(image.height):
if image.getpixel((x,y))< thresh:
image.putpixel((x,y), 0)
else:
image.putpixel((x,y), 255)
return image
def op_binarize(image1, thresh):
image = image1.convert('L')
for x in range(image.width):
for y in range(image.height):
if image.getpixel((x,y))< thresh:
image.putpixel((x,y), 255)
else:
image.putpixel((x,y), 0)
return image
for i in range(0, 257, 64):
image = binarize(extract, i)
image_op = op_binarize(extract, i)
display(image)
display(image_op)
print(pytesseract.image_to_string(image))
print(pytesseract.image_to_string(image_op))
JCB | - J JCB] -
d = []
with open("words.txt", "r") as f:
data = f.read()
d = data.split("\n")
for i in range(120, 200):
s_op = pytesseract.image_to_string(op_binarize(extract, i))
s = pytesseract.image_to_string(binarize(extract, i))
s_op = s_op.lower()
s = s.lower()
import string
ans = ans_op = ''
for c in s:
if c in string.ascii_lowercase:
ans = ans + c
for c_op in s_op:
if c_op in string.ascii_lowercase:
ans_op = ans_op + c_op
if ans is not '' and ans_op is not '':
if ans.upper() in d or ans_op.upper in d or ans_op.lower() in d or ans.lower() in d:
print(i)
print(ans)
print(ans_op)
<>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? <>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? <>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? <>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? <ipython-input-93-40c875798d2f>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? if ans is not '' and ans_op is not '': <ipython-input-93-40c875798d2f>:18: SyntaxWarning: "is not" with a literal. Did you mean "!="? if ans is not '' and ans_op is not '':
140 es luce 171 jcb jcb 190 jcb jcb 191 jcb jcb 192 jcb jjcb 193 jcb jcb 194 jcb jcb 195 jcb jcb 196 jcb jcb 197 jcb jcb 198 jcb jcb 199 jcb jcb
from PIL import Image, ImageDraw
from ipywidgets import interact
image = Image.open('perfect.jpg')
@interact(left=100, top=100, right=200, bottom=200)
def draw_box(left, top, right, bottom):
i = image.copy()
drawing_obj = ImageDraw.Draw(i)
drawing_obj.rectangle((left, top, right, bottom), fill = None, outline = 'red')
display(i)
import cv2 as cv
img = cv.imread('faces.jpg')
display(img)
array([[[115, 121, 90],
[138, 144, 113],
[150, 155, 128],
...,
[113, 117, 106],
[113, 116, 107],
[112, 115, 106]],
[[ 96, 101, 72],
[111, 116, 87],
[103, 108, 81],
...,
[100, 104, 93],
[105, 108, 99],
[108, 111, 102]],
[[204, 211, 184],
[194, 200, 175],
[139, 145, 122],
...,
[ 87, 88, 78],
[ 95, 96, 87],
[105, 106, 97]],
...,
[[ 43, 112, 79],
[ 42, 111, 78],
[ 41, 110, 77],
...,
[ 62, 122, 88],
[ 62, 122, 88],
[ 62, 122, 88]],
[[ 42, 109, 78],
[ 53, 120, 89],
[ 49, 116, 85],
...,
[ 73, 128, 95],
[ 51, 106, 73],
[ 61, 116, 83]],
[[ 42, 109, 78],
[ 53, 120, 89],
[ 49, 116, 85],
...,
[ 64, 117, 84],
[ 41, 94, 61],
[ 52, 105, 72]]], dtype=uint8)
g = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
import inspect
inspect.getmro(type(g))
(numpy.ndarray, object)
image = Image.fromarray(g, 'L')
display(image)
import numpy as np
s = np.array([10,20,30,40])
print(s)
d = np.array([s])
print(d)
[10 20 30 40] [[10 20 30 40]]
from PIL import Image
s = []
d = []
for i in range(0,256):
s.append(i)
for j in range(0,256):
d.append(s)
d = np.array(d)
display(Image.fromarray(d, "L"))
d.shape
(256, 256)
img.shape
(194, 259, 3)
first = img[0][3]
first
array([154, 158, 133], dtype=uint8)
re = np.reshape(g, (1,g.shape[0] * g.shape[1]))
print(re)
[[111 134 146 ... 101 78 89]]
random = np.full((120,120), 123, dtype = np.uint8)
display(Image.fromarray(random, "L"))
print(random)
[[123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] ... [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123]]
random[3:80, 60] = np.full((1, 77), 0, dtype = np.uint8)
display(Image.fromarray(random, 'L'))
print(random)
[[123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] ... [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123]]
random[80, 2: 60] = np.full((58), 0, dtype = np.uint8)
display(Image.fromarray(random, 'L'))
print(random)
[[123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] ... [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123] [123 123 123 ... 123 123 123]]
np.count_nonzero(random)
14265
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
image = cv.imread('face.jpg')
g = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(g)
print(face)
[[ 34 61 139 139]]
from PIL import Image, ImageDraw
im = Image.fromarray(g, mode='L')
dr = ImageDraw.Draw(im)
part = face.tolist()[0]
dr.rectangle(part, outline = 'yellow')
display(im)
from PIL import Image, ImageDraw
im = Image.fromarray(g, mode='L')
dr = ImageDraw.Draw(im)
part = face.tolist()[0]
dr.rectangle((part[0], part[1], part[0] + part[2], part[1] + part[3]), outline = 'red')
display(im)
image = cv.imread('faces_multi.gif')
display(image)
array([[[102, 87, 71],
[101, 86, 70],
[100, 86, 68],
...,
[ 83, 74, 61],
[ 84, 75, 62],
[ 83, 74, 61]],
[[101, 86, 70],
[100, 85, 69],
[ 99, 85, 67],
...,
[ 83, 74, 61],
[ 83, 74, 61],
[ 83, 74, 61]],
[[ 99, 84, 68],
[ 99, 84, 68],
[ 98, 84, 66],
...,
[ 83, 74, 61],
[ 82, 73, 60],
[ 81, 72, 59]],
...,
[[ 47, 116, 96],
[ 58, 127, 107],
[ 51, 120, 100],
...,
[ 58, 95, 79],
[ 56, 93, 77],
[ 43, 80, 64]],
[[ 48, 119, 99],
[ 55, 126, 106],
[ 38, 109, 89],
...,
[ 59, 96, 80],
[ 56, 93, 77],
[ 46, 83, 67]],
[[ 35, 107, 87],
[ 48, 120, 100],
[ 39, 110, 90],
...,
[ 61, 98, 82],
[ 58, 95, 79],
[ 50, 87, 71]]], dtype=uint8)
display(Image.fromarray(image))
pil = Image.open('faces_multi.gif')
op = pil.convert('L')
op.save('faces_multi.jpg')
b = cv.imread('faces_multi.jpg')
faces = face_cascade.detectMultiScale(b)
pil = Image.open('faces_multi.gif')
pil = pil.convert('P')
d = ImageDraw.Draw(pil)
for x, y, w, h in faces:
d.rectangle((x,y, x+w, y+h), outline = "red")
display(pil)
print(pil.mode)
P
b = cv.imread('faces_multi.jpg')
faces = face_cascade.detectMultiScale(b)
pil = Image.open('faces_multi.gif')
d = ImageDraw.Draw(pil)
for x, y, w, h in faces:
d.rectangle((x,y, x+w, y+h), outline = "red")
pil = pil.convert('RGB')
display(pil)
print(pil.mode)
RGB
def shf(faces):
pil = Image.open('faces_multi.jpg').convert('RGB')
d = ImageDraw.Draw(pil)
for x,y,w,h in faces:
d.rectangle((x,y,x+w,y+h), outline = 'orange')
display(pil)
c = cv.threshold(cv.imread('faces_multi.gif'), 150,255, cv.THRESH_BINARY)[1]
faces = face_cascade.detectMultiScale(c)
shf(faces)
for i in [1.05, 1.10, 1.15, 1.20, 1.25, 1.30]:
faces = face_cascade.detectMultiScale(cv.imread('faces_multi.gif'), i)
shf(faces)
#print(%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),i))
%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),1.05)
1.33 s ± 39.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),1.15)
558 ms ± 22.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),1.25)
352 ms ± 10.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),1.35)
293 ms ± 10.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit face_cascade.detectMultiScale(cv.imread('faces_multi.gif'),1.45)
283 ms ± 7.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)